<template>
  <div
    style="
      width: 100vw;
      height: 100vh;
      background: #eee;
      display: flex;
      align-items: center;
    "
  >
    <div
      style="
        height: 70%;
        width: 100%;
        display: flex;
        align-items: center;
        backgroundsize: 100% 100%;
        justify-content: flex-end;
      "
      :style="{ backgroundImage: `url(${this.imgUrl})` }"
    >
      <div
        v-loading="loading"
        element-loading-text="登录中..."
        style="
          width: 330px;
          height: 440px;
          overflow: hidden;
          margin-right: 50px;
        "
      >
        <iframe
          style="width: 100%; height: 100%; background: #eee"
          src="./login.html"
        ></iframe>
      </div>
    </div>
  </div>
</template>

<script>
import imgUrl from "../assets/background.png";

function getQueryString(key) {
  var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
  var result = window.location.search.substr(1).match(reg);
  return result ? decodeURIComponent(result[2]) : null;
}
export default {
  data() {
    return {
      imgUrl: imgUrl,
      loading: false,
    };
  },
  mounted() {
    // 获得code时
    if (window.location.href.includes("code")) {
      let code = getQueryString("code");
      console.error("code:", code);
      this.loading = true;
      this.clickFun(code);
      // 如果前后台都想自己完成的话，可以用nodejs作为后台简单点，也可以用其他后台语言，例如java或php
      // 道理一样的，可以加我微信号咨询 yizheng369
      // this.$alert(`将code: ${code} 传给后台，后台获取到个人信息，即可完成登录！`, '提示',{
      //   callback: that.clickFun.bind(that)
      // })
    }
  },
  methods: {
    async clickFun(code) {
      console.log("data", code);
      try {
        let rel = await this.$http.get("/api/wx?code=" + code);
        console.log("登录结果", rel);
        if(!rel){
          this.$alert("登录出错","报错",{
            type: 'error'
          });
          return
        }
        this.loading = false;
        this.$message({
          message: "登录成功",
          type: "success",
        });
        this.$router.push({
          path: "/home",
          query: rel // 带上后台返回的个人信息数据
        });
      } catch (error) {
        console.error('登录出错',error);
      }
    },
  },
};
</script>

<style>
</style>